package com.example.cyh.bczapp.Code.fragment;

import android.app.Fragment;
import android.content.Intent;
import android.os.Bundle;
import android.os.Looper;
import android.support.annotation.Nullable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.example.cyh.bczapp.Code.Activity.ChangePlan;
import com.example.cyh.bczapp.Code.Activity.LoadActivity;
import com.example.cyh.bczapp.Code.Activity.MainActivity;
import com.example.cyh.bczapp.Code.Activity.RememberActivity;
import com.example.cyh.bczapp.Code.BLL.PlanBLL;
import com.example.cyh.bczapp.Code.BLL.RemenberBll;
import com.example.cyh.bczapp.Code.BLL.WordGroupBLL;
import com.example.cyh.bczapp.Code.Model.PlanInfEntity;
import com.example.cyh.bczapp.Code.Model.RemenberInfEntity;
import com.example.cyh.bczapp.Code.Model.UserInfEntity;
import com.example.cyh.bczapp.Code.Model.WordGroupInfEntity;
import com.example.cyh.bczapp.R;
import com.jeremyfeinstein.slidingmenu.lib.SlidingMenu;
import com.jeremyfeinstein.slidingmenu.lib.app.SlidingFragmentActivity;

import java.util.ArrayList;

/**
 * Created by cyh on 2017/5/8.
 */

public class HomeFragment extends Fragment {
    //home碎片页面中的滑动试图
    private View AllView;
    private ViewPager viewPager;  //对应的viewPager
    private View viewplanmake;
    private View viewplaninf;
    private View viewother;
    private int oldPosition = 0;//记录上一次的页面key
    private int currentItem; // 当前页面  key
    private ArrayList<View> dots;
    private ArrayList<View> planlist;


    //背单词数据
    public PlanInfEntity mainplan;
    public UserInfEntity user;
    public RemenberInfEntity todayremenber;
    public WordGroupInfEntity mainwordGroup;

    public boolean hasplan = true;
    private boolean start = true;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        AllView = inflater.inflate(R.layout.fragment_home, container, false);
        if (start) {
            dots = new ArrayList<View>();
            dots.add(AllView.findViewById(R.id.dot_1));
            dots.add(AllView.findViewById(R.id.dot_2));
            dots.get(0).setBackgroundResource(R.drawable.dot_focused);
            LoadViewPager();
        }
        //改变滑动点
        dots.get(0).setBackgroundResource(R.drawable.dot_focused);
        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            ///在滚动事件中改变点的样式
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                // TODO Auto-generated method stub
                dots.get(oldPosition).setBackgroundResource(R.drawable.dot_oldfocused);
                dots.get(position).setBackgroundResource(R.drawable.dot_focused);

                oldPosition = position;
                currentItem = position;
            }

            @Override
            public void onPageSelected(int position) {
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        viewPager.setOnTouchListener(new View.OnTouchListener() {
            //在触摸事件中禁止父视图接受滑动事件以免冲突
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                int index = viewPager.getCurrentItem();
                if (index == 1)
                    getView().getParent().requestDisallowInterceptTouchEvent(true);
                return false;
            }
        });
        return AllView;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onActivityCreated(savedInstanceState);
        //获取信息
        new Thread(new Runnable() {
            @Override
            public void run() {
                MainActivity main = ((MainActivity) getActivity());
                PlanBLL pb = new PlanBLL();
                RemenberBll remenberBll = new RemenberBll();
                WordGroupBLL wordGroupBLL = new WordGroupBLL();
                //获取主要计划
                if (start) {
                    try {
                        if (main.user.U_PlanId != null)
                            mainplan = pb.GetPlan(main.user.U_PlanId);
                        else
                            mainplan = null;
                        if (mainplan != null) {
                            //获取记单词信息
                            todayremenber = remenberBll.GetTodayRemember(main.user.U_PlanId, String.valueOf(main.user.U_Id));
                            //获取计划的单词组信息
                            mainwordGroup = wordGroupBLL.getWordGroup(String.valueOf(mainplan.WG_id));
                        } else {
                            hasplan = false;
                            main.runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    ChangePlanView(hasplan);
                                    setplanbtlisten(hasplan);
                                }
                            });
                        }
                    } catch (Exception ex) {
                        Toast.makeText(main, ex.getMessage(), Toast.LENGTH_SHORT).show();
                    }
                }
                if (todayremenber == null && mainwordGroup == null)
                    return;
                try {
                    if (!main.user.U_PlanId.equals("") && mainplan != null) {
                        //更新ui线程
                        main.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                ChangePlanView(true);
                                //一共的单词
                                int allwordcount = mainwordGroup.WG_Count;
                                //已经背了的单词
                                int remenberwordcount;
                                if (mainplan.P_RemenberWord == null || mainplan.P_RemenberWord.equals(""))
                                    remenberwordcount = 0;
                                else
                                    remenberwordcount = mainplan.P_RemenberWord.split(",").length;
                                ChangePlanView(hasplan);
                                //更新UI
                                try {
                                    ((TextView) AllView.findViewById(R.id.over_day)).setText(((MainActivity) getActivity()).user.U_WorkDays == null ? "" : ((MainActivity) getActivity()).user.U_WorkDays);
                                    ((TextView) AllView.findViewById(R.id.remenber_word)).setText(String.valueOf(remenberwordcount));
                                    TextView name = (TextView) getActivity().findViewById(R.id.Lb_groupname);
                                    name.setText(mainwordGroup.WG_Name);

                                    TextView residue = (TextView) getActivity().findViewById(R.id.Lb_residuenumber);
                                    residue.setText(String.valueOf(allwordcount - remenberwordcount));

                                    TextView tr = (TextView) getActivity().findViewById(R.id.Lb_todayworknumber);
                                    if (!todayremenber.equals(new RemenberInfEntity())) {
                                        if (todayremenber.R_RWord == "" || todayremenber.R_RWord == null)
                                            tr.setText("0");
                                        else
                                            tr.setText(String.valueOf(todayremenber.R_RWord.split(",").length));
                                    } else
                                        tr.setText("0");
                                    TextView over = (TextView) getActivity().findViewById(R.id.Lb_over);
                                    over.setText("已完成:" + String.valueOf(remenberwordcount) + "/" + String.valueOf(allwordcount));
                                    //进度条
                                    ProgressBar pb = (ProgressBar) getActivity().findViewById(R.id.my_progress);
                                    pb.setMax(allwordcount);
                                    pb.setProgress(remenberwordcount);
                                    setplanbtlisten(hasplan);
                                } catch (Exception Ex) {
                                    Toast.makeText(getActivity(), Ex.getMessage(), Toast.LENGTH_SHORT).show();

                                }
                            }
                        });
                    } else {
                        Looper.prepare();
                        Toast.makeText(main, "用户计划信息丢失", Toast.LENGTH_SHORT).show();
                        Looper.loop();
                    }
                } catch (Exception ex) {
                    Looper.prepare();
                    Toast.makeText(main, ex.getMessage(), Toast.LENGTH_SHORT).show();
                    Looper.loop();
                }
            }
        }).start();
        ((Button) getActivity().findViewById(R.id.Bt_Star)).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //开始背单词
                Intent intent = new Intent(getActivity(), RememberActivity.class);
                intent.putExtra("user", ((MainActivity) getActivity()).user);
                intent.putExtra("plan", mainplan);
                getActivity().startActivity(intent);
            }
        });
    }

    public void ChangePlanView(boolean hasplan) {
        viewPager.removeAllViews();
        planlist.clear();
        planlist.add(hasplan ? viewplaninf : viewplanmake);
        planlist.add(viewother);
        viewPager.getAdapter().notifyDataSetChanged();
    }

    private void LoadViewPager() {
        //viewpage  设置
        viewPager = (ViewPager) AllView.findViewById(R.id.viewpager_plan);
        LayoutInflater lf = getActivity().getLayoutInflater().from(getActivity());
        viewplaninf = lf.inflate(R.layout.viewpage_planinf, null);
        viewplanmake = lf.inflate(R.layout.viewpage_makeplan, null);
        viewother = lf.inflate(R.layout.viewpage_otherinf, null);
        // 将要分页显示的View装入数组中
        planlist = new ArrayList<View>();
        planlist.add(viewplanmake);
        planlist.add(viewother);
        MyPagerAdapter pagerAdapter = new MyPagerAdapter();
        viewPager.setAdapter(pagerAdapter);
        viewPager.setCurrentItem(0);
    }

    public void setplanbtlisten(boolean hasplan) {
        //根据有无计划为相应按钮添加点击事件
        View.OnClickListener listener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //跳转计划制定页面
                Intent intent = new Intent(getActivity(), ChangePlan.class);
                intent.putExtra("user", ((MainActivity) getActivity()).user);
                getActivity().startActivity(intent);
            }
        };
        if (!hasplan) {
            ((Button) getActivity().findViewById(R.id.bt_makeplan)).setOnClickListener(listener);
        } else {
            ((Button) getActivity().findViewById(R.id.bt_changeplan)).setOnClickListener(listener);
        }
    }

    //适配器内部类
    class MyPagerAdapter extends PagerAdapter {


        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            View layout = planlist.get(position);
            container.addView(layout);
            return layout;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            View layout = planlist.get(position);
            container.removeView(layout);
        }

        @Override
        public boolean isViewFromObject(View arg0, Object arg1) {
            return arg0 == arg1;

        }

        @Override
        public int getCount() {
            return planlist.size();
        }

        @Override
        public int getItemPosition(Object object) {
            // TODO Auto-generated method stub
            return POSITION_NONE;
        }

    }
}



